package com.fenghuaxz.rpcframework;

import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.internal.PlatformDependent;

import java.util.concurrent.ConcurrentMap;

public class IChannelGroup extends DefaultChannelGroup{

    private final ConcurrentMap<String,Channel> shortId = PlatformDependent.newConcurrentHashMap();
    private final ConcurrentMap<String,Channel> longId = PlatformDependent.newConcurrentHashMap();

    public IChannelGroup(EventExecutor executor) {
        super(executor);
    }

    public Channel find(String channelId){
        Channel c = shortId.get(channelId);
        return c != null ? c : longId.get(channelId);
    }

    @Override
    public boolean add(Channel channel) {
        ChannelId channelId = channel.id();
        this.shortId.put(channelId.asShortText(),channel);
        this.longId.put(channelId.asLongText(),channel);
        return super.add(channel);
    }

    @Override
    public boolean remove(Object o) {
        if (o instanceof Channel){
            ChannelId channelId = ((Channel) o).id();
            this.shortId.remove(channelId.asShortText());
            this.longId.remove(channelId.asLongText());
        }
        return super.remove(o);
    }

    @Override
    public void clear() {
        super.clear();
        this.shortId.clear();
        this.longId.clear();
    }
}
